package com.ruoyi.web.controller.module.thirdpard;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.market.domain.Banner;
import com.ruoyi.market.service.IBannerService;
import com.ruoyi.thirdpart.domain.UserAuth;
import com.ruoyi.thirdpart.service.IUserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;

/**
 * 用户授权
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/thirdpart/userauth")
public class UserAuthController extends BaseController
{
    @Autowired
    private IUserAuthService userAuthService;

    /**
     * 微信 公众号 登录
     */
    @PostMapping("/oauth2")
    public AjaxResult oauth2(@RequestBody UserAuth userAuth)
    {
        AjaxResult ajax = AjaxResult.success();
        String token = userAuthService.wxOauth2(userAuth.getCode(), userAuth.getShopId(), userAuth.getInviteId());
        ajax.put(AjaxResult.DATA_TAG, token);
        return ajax;
    }

    // 微信服务调用接口
    @RequestMapping(value = "/weChatTestV", method = RequestMethod.GET)
    public AjaxResult weChatTestV(HttpServletRequest request, HttpServletResponse response) {
        // 1、验证消息的确来自微信服务器
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        // 将微信echostr返回给微信服务器
        try (OutputStream os = response.getOutputStream()) {
            String sha1 = getSHA1("ganluhua1234", timestamp, nonce, "");

            // 和signature进行对比
            if (sha1.equals(signature)) {
                // 返回echostr给微信
                os.write(URLEncoder.encode(echostr, "UTF-8").getBytes());
                os.flush();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 用SHA1算法生成安全签名
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @param encrypt   密文
     * @return 安全签名
     * @throws Exception
     */
    public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws Exception {
        try {
            String[] array = new String[] { token, timestamp, nonce, encrypt };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
